﻿using MiniExcelLibs;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System;
using System.Security.Cryptography;
using System.Collections.ObjectModel;
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using System.Windows.Controls.Primitives;
using Microsoft.Win32;
using NPOI.SS.UserModel;
using HalconDotNet;
using System.ComponentModel;
using System.IO.Compression;
using NPOI.SS.Formula.Functions;
using DetectApp.Display;
using System.Threading;
using NPOI.OpenXmlFormats.Dml;
using static System.Net.Mime.MediaTypeNames;
using NPOI.Util;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using NPOI.XSSF.UserModel;
using System.Diagnostics;
using NPOI.HPSF;
using System.Drawing.Imaging;




namespace DetectApp;

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    private readonly double _height10 = 0.7;
    private readonly double _height20 = 0.3;
    private readonly double _height5 = 1.6;
    private string _imagePath = "e:/images";
    private string _measurePath = "e:/手动量测";
    private readonly double _width10 = 0.9;
    private readonly double _width20 = 0.4;
    private readonly double _width5 = 1.9;
    private double _cicleDiameter = 3000;
    private System.Windows.Shapes.Ellipse _circle;
    private bool _disDraw = false;
    private ScaleTransform _dscaleTransform;
    private Point _dstartPoint;
    private TransformGroup _dtransformGroup;
    private TranslateTransform _dtranslateTransform;
    private System.Windows.Shapes.Ellipse _ellipse;
    private int _gridHeight;
    private int _gridWidth;
    private int _imageHeight = 3100;
    private int _imageWidth = 3200;
    private bool _isDraw = false;
    private List<MeasureResult> _measureRsults;

    public static string ?CurWafer { get; set; }

    private List<ResultInfo> _results = new List<ResultInfo>();
    private ScaleTransform _scaleTransform;
    private Point _startPoint;
    private TextBlock _textBlock;
    private TransformGroup _transformGroup;
    private TranslateTransform _translateTransform;
    private WriteableBitmap _writeableBitmap = new WriteableBitmap(3200, 3100, 96, 96, PixelFormats.Pbgra32, null);
    private ObservableCollection<WaferInfo> Box = new();

    //量测结果
    public Dictionary<string, List<MeasureResult>> _dicAllMeasures;
    //量测渲染图像
    public Dictionary<string, RenderTargetBitmap> _dicAllRecordImage;
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = this;
    }

    public enum LenType
    {
        X5,
        X10,
        X20,
        X50,
        X100,
    }

    private void AddCross(Point point, int len)
    {
        DrawCanvas.Children.Remove(_circle);
        _circle = new System.Windows.Shapes.Ellipse
        {
            Width = len,
            Height = len,
            Stroke = Brushes.Red,
            StrokeThickness = 10,
        };
        Canvas.SetLeft(_circle, point.X - len / 2); Canvas.SetTop(_circle, point.Y - len / 2);
        DrawCanvas.Children.Add(_circle);
    }

    private void AddId(Point point, int id, int len)
    {
        TextBlock textBlock = new()
        {
            Text = $"{id}",
            FontSize = 120,
            Foreground = Brushes.AliceBlue,
            Tag = id,
        };
        Canvas.SetLeft(textBlock, point.X - len / 2); Canvas.SetTop(textBlock, point.Y - len / 2);
        DrawCanvas.Children.Add(textBlock);
    }

    private void ClearId()
    {
        List<TextBlock> textBlocks = new();
        foreach (var item in DrawCanvas.Children)
        {
            if (item is TextBlock textBlock) textBlocks.Add(textBlock);
        }
        foreach (var item1 in textBlocks)
        {
            DrawCanvas.Children.Remove(item1);
        }
    }

    private void BtExcel_Click(object sender, RoutedEventArgs e)
    {
        using var db = new ResultDb();
        List<ExcelInfo> excelInfos = new List<ExcelInfo>();
        if (CbBoxID.SelectedItem is string boxPath)
        {
            var selectPath = Path.Combine(_imagePath, boxPath);

            List<Dictionary<string, object>> keyValuePairs = new List<Dictionary<string, object>>();
            var dict = new Dictionary<string, object>();
            IWorkbook workbook = WorkbookFactory.Create("模版.xlsx");
            ISheet sheet = workbook.GetSheetAt(0);
            IRow row = (IRow)sheet.GetRow(2);
            row.GetCell(10).SetCellValue("机台1");
            row.GetCell(2).SetCellValue($"{boxPath}");
            int calId = 0;
            List<int> runtimes = new List<int>();
            string productName = string.Empty;
            foreach (var fileItem in Directory.EnumerateDirectories(selectPath).Select(dire => dire.Split("\\").Last()))
            {
                int imagecount = Directory.EnumerateFiles(Path.Combine(selectPath, fileItem)).Count();
                var runtimefile = Path.Combine(selectPath, fileItem, "运行时长.txt");
                if (File.Exists(runtimefile))
                {
                    TextReader reader = new StreamReader(runtimefile);
                    string? strruntime = reader.ReadLine();
                    reader.Close();
                    if (strruntime != null && strruntime.Contains(","))
                    {
                        var infos = strruntime.Split(",");
                        if (infos.Length == 2)
                        {
                            if (int.TryParse(infos[0], out int runTime))
                            {
                                runtimes.Add(runTime);
                            }
                            productName = infos[1];
                        }
                    }
                }
                var strsolot = fileItem.Split("_");
                row = (IRow)sheet.GetRow(8 + calId);
                if (strsolot.Length == 2)
                {
                    var slot = strsolot[0].Substring(strsolot[0].Length - 2, 2);
                    if (int.TryParse(slot, out int id))
                    {
                        var wafer = db.Results.Include(r => r.Defects).Where(r => r.BoxId == boxPath && r.WaferId == fileItem);
                        var a = wafer.ToList();
                        if (wafer.Count() < imagecount - 1 || a.Any(d => d.Defects.Count == 0))
                        {
                            MessageBox.Show($"插槽：{id}内的图片未判定完！");
                            return;
                        }

                        row.GetCell(0).SetCellValue(strsolot[0]);
                        for (int i = 0; i < 32; i++)
                        {
                            int defectCount = wafer.Where(w => w.Defects.Any(d => d.BinCode == i)).Count();
                            //if (i == 0 && defectCount == imagecount - 1)
                            //{
                            //    Directory.Delete(Path.Combine(selectPath, fileItem), true);
                            //}
                            if (_defectClsList.Any(d => d.BinCode == i))
                            {
                                string defectName = _defectClsList.First(d => d.BinCode == i).DefectName;
                                row.GetCell(i + 1).SetCellValue(defectCount);
                            }
                            else
                            {
                                row.GetCell(i + 1).SetCellValue(0);
                            }
                        }
                    }
                }
                calId++;
            }
            if (runtimes.Count > 0)
            {
                int totalruntime = runtimes.Sum();
                int averuntime = (int)runtimes.Average();
                int maxruntime = runtimes.Max();
                int minruntime = runtimes.Min();
                row = (IRow)sheet.GetRow(4);

                row.GetCell(0).SetCellValue($"{totalruntime / 60}m {totalruntime % 60}s");
                row.GetCell(2).SetCellValue($"{maxruntime / 60}m {maxruntime % 60}s");
                row.GetCell(4).SetCellValue($"{minruntime / 60}m {minruntime % 60}s");
                row.GetCell(6).SetCellValue($"{averuntime / 60}m {averuntime % 60}s");

                row = (IRow)sheet.GetRow(2);
                row.GetCell(0).SetCellValue(productName);
            }
            sheet.ForceFormulaRecalculation = true;

            if (!Directory.Exists(_systemData.SaveImagePath))
            {
                MessageBox.Show("路径不存在");
                return;
            }
            string savePath = Path.Combine(_systemData.SaveImagePath, boxPath + ".xlsx");

            if (File.Exists(savePath))
                File.Delete(savePath);
            FileStream fs = new FileStream(savePath, FileMode.Create, FileAccess.ReadWrite);
            workbook.Write(fs);
            fs.Close();
            GC.Collect();
            GC.WaitForPendingFinalizers();
            //if (MessageBox.Show("是否删除图片", "询问", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            //{
            //}
            //ZipTipView zipTipView = new ZipTipView(selectPath, Path.Combine(_imagePath, boxPath + ".zip"));
            //zipTipView.ShowDialog();

            //Directory.Delete(selectPath, true);
            MessageBox.Show("导出完成");
        }
    }

    /// <summary>
    /// 盒子ID选择更换事件
    /// </summary>
    /// <param name="sender">
    /// </param>
    /// <param name="e">
    /// </param>
    private void CbBoxID_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
    {
        Box.Clear();
        for (int i = 0; i < 25; i++)
        {
            Box.Add(new WaferInfo { Id = $"{i + 1}", IsShow = false, });
        }
        if (CbBoxID.SelectedItem is string selectStr)
        {
            if (string.IsNullOrEmpty(selectStr)) return;
            var selectPath = Path.Combine(_imagePath, selectStr);
            if (!Directory.Exists(selectPath)) return;
            foreach (var fileItem in Directory.EnumerateDirectories(selectPath).Select(dire => dire.Split("\\").Last()))
            {
                var strsolot = fileItem.Split("_");
                if (strsolot.Length == 2)
                {
                    var slot = strsolot[0].Substring(strsolot[0].Length - 2, 2);
                    if (int.TryParse(slot, out int id))
                    {
                        Box[id - 1].IsShow = true;
                        Box[id - 1].FilePath = fileItem;
                    }
                }
            }

            LvWafer.SelectedIndex = 0;
        }
    }

    private void ClearColor()
    {
        Int32Rect rect = new Int32Rect(0, 0, _imageWidth, _imageHeight);
        byte[] pixels = new byte[_imageWidth * _imageHeight * 4]; // 4 bytes per pixel for Pbgra32 format
        _writeableBitmap.CopyPixels(rect, pixels, _imageWidth * 4, 0);

        // 修改像素数据来绘制网格
        for (int y = 0; y < _imageHeight; y++)
        {
            for (int x = 0; x < _imageWidth; x++)
            {
                int index = (y * _imageWidth + x) * 4; // 4 bytes per pixel
                byte r = 0; // Red
                byte g = 0; // Green
                byte b = 0; // Blue
                byte a = 255; // Alpha (fully visible)

                // 根据网格大小改变颜色
                if ((x % _gridWidth == 0) || (y % _gridHeight == 0))
                {
                    r = 255; // Red
                    g = 255; // Green
                    b = 255; // Blue
                }

                pixels[index + 0] = r; // Red
                pixels[index + 1] = g; // Green
                pixels[index + 2] = b; // Blue
                pixels[index + 3] = a; // Alpha
            }
        }
        _writeableBitmap.WritePixels(rect, pixels, _imageWidth * 4, 0);
    }

    private void DrawCanvas_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
        _isDraw = true;
        _startPoint = e.GetPosition(DrawCanvas);

        DrawCanvas.CaptureMouse();
    }

    private void DrawCanvas_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
        _isDraw = false;
        DrawCanvas.ReleaseMouseCapture();
    }

    private void DrawCanvas_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
    {
        Point tempPoint;

        tempPoint = e.GetPosition(DrawCanvas);
        if (!_isDraw)
        {
            //_textBlock.Margin = new Thickness(tempPoint.X + 20, tempPoint.Y - 20, 0, 0);
            tempPoint = e.GetPosition(DrawCanvas);
            Tbrc.Text = $"R:{tempPoint.Y:f0},C:{tempPoint.X:f0}";
        }
        else
        {
            _translateTransform.X += tempPoint.X - _startPoint.X;
            _translateTransform.Y += tempPoint.Y - _startPoint.Y;
        }
    }

    private void DrawCanvas_MouseWheel(object sender, System.Windows.Input.MouseWheelEventArgs e)
    {
        var point = e.GetPosition(DrawCanvas);
        ZoomImage(point, e.Delta * 0.0005);
    }

    private void DrawGrid(LenType lenType, WriteableBitmap writeableBitmap)
    {
        switch (lenType)
        {
            case LenType.X5:
                _gridWidth = (int)(_width5 * 10);
                _gridHeight = (int)(_height5 * 10);

                break;

            case LenType.X10:
                _gridWidth = (int)(_width10 * 10d);
                _gridHeight = (int)(_height10 * 10);

                break;

            case LenType.X20:
                _gridWidth = (int)(_width20 * 10);
                _gridHeight = (int)(_height20 * 10);

                break;

            case LenType.X50:
                break;

            case LenType.X100:
                break;

            default:
                break;
        }
        // 创建一个WriteableBitmap对象

        int width = writeableBitmap.PixelWidth;
        int height = writeableBitmap.PixelHeight;
        // 获取像素数据
        Int32Rect rect = new Int32Rect(0, 0, width, height);
        byte[] pixels = new byte[width * height * 4]; // 4 bytes per pixel for Pbgra32 format
        writeableBitmap.CopyPixels(rect, pixels, width * 4, 0);

        // 修改像素数据来绘制网格
        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < width; x++)
            {
                int index = (y * width + x) * 4; // 4 bytes per pixel
                byte r = 0; // Red
                byte g = 0; // Green
                byte b = 0; // Blue
                byte a = 255; // Alpha (fully visible)

                // 根据网格大小改变颜色
                if ((x % _gridWidth == 0) || (y % _gridHeight == 0))
                {
                    r = 255; // Red
                    g = 255; // Green
                    b = 255; // Blue
                }

                pixels[index + 0] = r; // Red
                pixels[index + 1] = g; // Green
                pixels[index + 2] = b; // Blue
                pixels[index + 3] = a; // Alpha
            }
        }

        // 将修改后的像素数据写回到WriteableBitmap
        writeableBitmap.WritePixels(rect, pixels, width * 4, 0);

        // 将WriteableBitmap转换为BitmapSource以用于Image控件等。
    }
    private HImage? _curImage;
    private string _curPath = string.Empty;
    /// <summary>
    /// 晶圆不同位置图片切换事件
    /// </summary>
    /// <param name="sender">
    /// </param>
    /// <param name="e">
    /// </param>
    private void LbResults_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
    {
        ClearColor();
        BdAll.Visibility = Visibility.Visible;

        if (!string.IsNullOrEmpty(_curPath) && _measureRsults.Count != 0)
        {
            if (!_dicAllMeasures.ContainsKey(_curPath) && _measureRsults.Count != 0)
            {
                List<MeasureResult> mrs = new List<MeasureResult>();
                _measureRsults.ForEach(m => mrs.Add(m));
                _dicAllMeasures.Add(_curPath, mrs);
                _dicAllRecordImage.Add(_curPath, mDisp.GetWindowContent());
            }
            else if (_measureRsults.Count != 0)
            {
                List<MeasureResult> mrs = _dicAllMeasures[_curPath];
                _measureRsults.ForEach(m => mrs.Add(m));
                _dicAllMeasures[_curPath] = mrs;
                _dicAllRecordImage[_curPath] = mDisp.GetWindowContent();
            }
        }


        _measureRsults.Clear();

        if (LbResults.SelectedItem is ResultInfo rst)
        {
            foreach (var con in DrawCanvas.Children)
            {
                if (con is TextBlock textBlock && textBlock.Tag is int ivalue)
                {
                    if (ivalue == rst.Id)
                    {
                        textBlock.Background = Brushes.DarkBlue;
                    }
                    else
                    {
                        textBlock.Background = Brushes.Transparent;
                    }
                }
            }

            _curPath = rst.FullPath;

            HImage hImage = new HImage(rst.FullPath);
            _curImage = hImage;
            mDisp.Display(hImage);
            mDisp.ClearAllROI();
            mDisp.ClearVisual();
            if (_dicAllMeasures.TryGetValue(rst.FullPath, out List<MeasureResult> mrs))
            {

                if (mrs == null) return;
                foreach (var m in mrs)
                {
                    foreach (var l in m.AllLines)
                    {
                        try
                        {
                            mDisp.CvDisplay2.Children.Add(l);
                        }
                        catch
                        {
                        }
                    }
                    mDisp.DisplayText($"{m.Distance:f1}um", Colors.Red, 60, m.TextPoint);
                }
            }
        }
    }

    private void SetColor(Point startPoint, Point endPoint)
    {
        Int32Rect rect = new Int32Rect(0, 0, _imageWidth, _imageHeight);
        byte[] pixels = new byte[_imageWidth * _imageHeight * 4]; // 4 bytes per pixel for Pbgra32 format
        _writeableBitmap.CopyPixels(rect, pixels, _imageWidth * 4, 0);

        //1.计算startPoint点所处网格左上角的点
        var startInx = (int)startPoint.X / _gridWidth;
        var startIny = (int)startPoint.Y / _gridHeight;
        //2.计算EndPoint点所处网格的右下角的点
        var endInx = (int)endPoint.X / _gridWidth;
        var endIny = (int)endPoint.Y / _gridHeight;
        // 修改像素数据来绘制网格
        for (int y = 0; y < _imageHeight; y++)
        {
            for (int x = 0; x < _imageWidth; x++)
            {
                int index = (y * _imageWidth + x) * 4; // 4 bytes per pixel
                                                       // 根据网格大小改变颜色
                if ((x > startInx * _gridWidth & x < endInx * _gridWidth + _gridWidth) && (y > startIny * _gridHeight && y < endIny * _gridHeight + _gridHeight))
                {
                    byte r = pixels[index + 0]; // Red
                    byte b = pixels[index + 2]; // Blue
                    byte a = pixels[index + 3];
                    byte g = pixels[index + 1];
                    if (pixels[index + 1] == 0)
                    {
                        r = 0;
                        b = 0;
                        g = 255; // Green
                    }
                    else if (pixels[index + 1] == 255 && pixels[index] == 0)
                    {
                        r = 0;
                        b = 0;
                        g = 0;
                    }
                    pixels[index + 0] = r; // Red
                    pixels[index + 1] = g; // Green
                    pixels[index + 2] = b; // Blue
                    pixels[index + 3] = a; // Alpha
                }
            }
        }
        _writeableBitmap.WritePixels(rect, pixels, _imageWidth * 4, 0);
    }

    private void Window_Closed(object sender, System.EventArgs e)
    {
        Close();
    }

    /// <summary>
    /// 窗口加载事件
    /// </summary>
    /// <param name="sender">
    /// </param>
    /// <param name="e">
    /// </param>
    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        _machineData = new MachineData();
        Load_ID();
        //try
        //{

        //    _machineData=new MachineData();

        //    string filePath = "systemdata.json";
        //    if (File.Exists(filePath))
        //    {
        //        using (var filestream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
        //        {
        //            _systemData = JsonSerializer.Deserialize<systemData>(filestream) ?? new();
        //        }
        //    }
        //    else
        //    {
        //        _systemData = new systemData();
        //    }
        //    _measurePath = _systemData.MeasurePath;
        //    _imagePath = _systemData.ImagePath;
        //    _measureRsults = new(); //量测结果集合
        //    _dicAllMeasures = new();//对应图像名称的所有量测集合
        //    _dicAllRecordImage = new();//渲染图像集合
        //    mDisp.MeasureResults = _measureRsults;

        //    LvWafer.ItemsSource = Box;
        //    var dires = Directory.EnumerateDirectories(_imagePath).Select(dire => new DirectoryInfo(dire).Name).ToList();

        //    //创建数据库
        //    if (!Directory.Exists("Products")) Directory.CreateDirectory("Products");
        //    using ResultDb resultDb = new();
        //    resultDb.Database.EnsureCreated();

        //    _textBlock = new TextBlock()
        //    {
        //        FontSize = 16,
        //        Background = Brushes.LightBlue,
        //        //HorizontalAlignment = HorizontalAlignment.Left,
        //        //VerticalAlignment = VerticalAlignment.Top,
        //    };
        //    _textBlock.Visibility = Visibility.Collapsed;
        //    _textBlock.Width = 120;
        //    _textBlock.Height = 24;
        //    Gd.Children.Add(_textBlock);

        //    _scaleTransform = new ScaleTransform();
        //    _translateTransform = new TranslateTransform();
        //    _transformGroup = new TransformGroup();
        //    _transformGroup.Children.Add(_scaleTransform);
        //    _transformGroup.Children.Add(_translateTransform);
        //    DrawCanvas.RenderTransform = _transformGroup;

        //    _dscaleTransform = new ScaleTransform();
        //    _dtranslateTransform = new TranslateTransform();
        //    _dtransformGroup = new TransformGroup();
        //    _dtransformGroup.Children.Add(_dscaleTransform);
        //    _dtransformGroup.Children.Add(_dtranslateTransform);
        //    //DispCanvas.RenderTransform = _dtransformGroup;

        //    _ellipse = new() { Width = _cicleDiameter, Height = _cicleDiameter, SnapsToDevicePixels = true, Stroke = Brushes.Yellow, StrokeThickness = 3 };
        //    Canvas.SetLeft(_ellipse, (_imageWidth - _cicleDiameter) / 2);
        //    Canvas.SetTop(_ellipse, (_imageHeight - _cicleDiameter) / 2);
        //    DrawCanvas.Children.Add(_ellipse);

        //    DrawGrid(LenType.X10, _writeableBitmap);
        //    ImageControl.Source = _writeableBitmap;
        //    System.Windows.Shapes.Polygon rectangle = new();
        //    rectangle.Points.Add(new Point(0, 0));
        //    rectangle.Points.Add(new Point(100, 0));
        //    rectangle.Points.Add(new Point(50, 100));

        //    rectangle.Fill = Brushes.Red;
        //    Canvas.SetLeft(rectangle, (_imageWidth - 100) / 2); Canvas.SetTop(rectangle, (80) / 2);
        //    DrawCanvas.Children.Add(rectangle);
        //    //DispId();

        //    if (File.Exists(_savePath))
        //    {
        //        using (var filestream = new FileStream(_savePath, FileMode.Open, FileAccess.Read))
        //        {
        //            _defectClsList = JsonSerializer.Deserialize<List<DefectCls>>(filestream) ?? new();
        //        }
        //    }

        //    LogView logView = new LogView(_systemData.PassWord);
        //    logView.Owner = this;
        //    logView.ShowInTaskbar = false;
        //    if (logView.ShowDialog() == false)
        //    {
        //        App.Current.Shutdown();
        //    }
        //}
        //catch (Exception ex)
        //{

        //    MessageBox.Show($"初始化软件异常：{ex.Message} 位置：{ex.StackTrace}");
        //}



        //测试用--------------------
        //HImage hImage = new HImage(@"C:\Users\22950\Documents\WeChat Files\wxid_i6y87wwans4q12\FileStorage\File\2024-02\X50\X50\15.bmp");
        //_curImage = hImage;
        //mDisp.Display(hImage);
    }

    private void Load_ID()
    {

        try
        {

          
            if (CbMaineID.SelectedIndex == -1)
            {
                MessageBox.Show("请选择设备ID");
                return;
            }


            string filePath = "systemdata.json";
            if (_machineData.ID!=0)
            {
              filePath = "systemdata"+ _machineData.ID + ".json";
            }
           


            if (File.Exists(filePath))
            {
                using (var filestream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                {
                    _systemData = JsonSerializer.Deserialize<systemData>(filestream) ?? new();
                }
            }
            else
            {
                _systemData = new systemData();
            }
            _measurePath = _systemData.MeasurePath;
            _imagePath = _systemData.ImagePath;
            _measureRsults = new(); //量测结果集合
            _dicAllMeasures = new();//对应图像名称的所有量测集合
            _dicAllRecordImage = new();//渲染图像集合
            mDisp.MeasureResults = _measureRsults;

            LvWafer.ItemsSource = Box;

     
            var dires = Directory.EnumerateDirectories(_imagePath).Select(dire => new DirectoryInfo(dire).Name).ToList();

            //创建数据库
            if (!Directory.Exists("Products")) Directory.CreateDirectory("Products");
            using ResultDb resultDb = new();
            resultDb.Database.EnsureCreated();

            _textBlock = new TextBlock()
            {
                FontSize = 16,
                Background = Brushes.LightBlue,
                //HorizontalAlignment = HorizontalAlignment.Left,
                //VerticalAlignment = VerticalAlignment.Top,
            };
            _textBlock.Visibility = Visibility.Collapsed;
            _textBlock.Width = 120;
            _textBlock.Height = 24;
            Gd.Children.Add(_textBlock);

            _scaleTransform = new ScaleTransform();
            _translateTransform = new TranslateTransform();
            _transformGroup = new TransformGroup();
            _transformGroup.Children.Add(_scaleTransform);
            _transformGroup.Children.Add(_translateTransform);
            DrawCanvas.RenderTransform = _transformGroup;

            _dscaleTransform = new ScaleTransform();
            _dtranslateTransform = new TranslateTransform();
            _dtransformGroup = new TransformGroup();
            _dtransformGroup.Children.Add(_dscaleTransform);
            _dtransformGroup.Children.Add(_dtranslateTransform);
            //DispCanvas.RenderTransform = _dtransformGroup;

            _ellipse = new() { Width = _cicleDiameter, Height = _cicleDiameter, SnapsToDevicePixels = true, Stroke = Brushes.Yellow, StrokeThickness = 3 };
            Canvas.SetLeft(_ellipse, (_imageWidth - _cicleDiameter) / 2);
            Canvas.SetTop(_ellipse, (_imageHeight - _cicleDiameter) / 2);
            DrawCanvas.Children.Add(_ellipse);

            DrawGrid(LenType.X10, _writeableBitmap);
            ImageControl.Source = _writeableBitmap;
            System.Windows.Shapes.Polygon rectangle = new();
            rectangle.Points.Add(new Point(0, 0));
            rectangle.Points.Add(new Point(100, 0));
            rectangle.Points.Add(new Point(50, 100));

            rectangle.Fill = Brushes.Red;
            Canvas.SetLeft(rectangle, (_imageWidth - 100) / 2); Canvas.SetTop(rectangle, (80) / 2);
            DrawCanvas.Children.Add(rectangle);
            //DispId();

            if (File.Exists(_savePath))
            {
                using (var filestream = new FileStream(_savePath, FileMode.Open, FileAccess.Read))
                {
                    _defectClsList = JsonSerializer.Deserialize<List<DefectCls>>(filestream) ?? new();
                }
            }

            LogView logView = new LogView(_systemData.PassWord);
            logView.Owner = this;
            logView.ShowInTaskbar = false;
            if (logView.ShowDialog() == false)
            {
                App.Current.Shutdown();
            }
        }
        catch (Exception ex)
        {

            MessageBox.Show($"初始化软件异常：{ex.Message} 位置：{ex.StackTrace}");
        }

    }




    public MachineData _machineData;
    private systemData _systemData;
    private List<DefectCls> _defectClsList;
    private string _savePath = "shortconfig.json";

    private void ZoomImage(Point point, double scale)
    {
        if (scale + _scaleTransform.ScaleX > 1 && scale + _scaleTransform.ScaleY > 1)
        {
            _scaleTransform.ScaleX += scale;
            _scaleTransform.ScaleY += scale;
            _translateTransform.X -= point.X * scale;
            _translateTransform.Y -= point.Y * scale;
        }
        else
        {
            _scaleTransform.ScaleX = 1;
            _scaleTransform.ScaleY = 1;
            _translateTransform.X = 0;
            _translateTransform.Y = 0;
        }
    }

    /// <summary>
    /// 晶圆切换事件
    /// </summary>
    /// <param name="sender">
    /// </param>
    /// <param name="e">
    /// </param>
    private void LvWafer_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        using var db = new ResultDb();

        if (CbBoxID.SelectedItem is string boxPath && LvWafer.SelectedItem is WaferInfo waferInfo)
        {
            string waferPath = waferInfo.FilePath;
            CurWafer = waferInfo.FilePath;
            var selectPath = Path.Combine(_imagePath, boxPath, waferPath);

            if (!Directory.Exists(selectPath))
                return;
            var fileNames = Directory.EnumerateFiles(selectPath).ToList();
            foreach (var file in fileNames)
            {
                GenPartImage(file);
            }
            _results = Directory.EnumerateFiles(selectPath).Select(sp =>
            {
                int id = GetId(Path.GetFileNameWithoutExtension(sp));
                int sortId = GetSortId(Path.GetFileNameWithoutExtension(sp));
                ResultInfo resultCls = new ResultInfo
                {
                    BoxId = boxPath,
                    WaferId = waferPath,
                    PosId = Path.GetFileNameWithoutExtension(sp),
                    IsOK = null,
                    FullPath = sp,
                    Id = id,
                    SortId = sortId,
                };
                if (resultCls.Id == 0) resultCls.SId = resultCls.PosId;
                else resultCls.SId = resultCls.Id.ToString();
                if (db.Results.Any(r => r.FullPath == sp))
                {
                    resultCls.IsOK = db.Results.First(r => r.FullPath == sp).IsOK;
                    resultCls.Defects = db.Results.Include(r => r.Defects).First(r => r.FullPath == sp).Defects;
                }

                return resultCls;
            }).ToList();
            if (_results.Any(r => r.PosId == "运行时长"))
            {
                var rst1 = _results.First(r => r.PosId == "运行时长");
                _results.Remove(rst1);
            }
            ClearId();
            foreach (var rstItem in _results)
            {
                if (rstItem.PosId.Contains("-"))
                {
                    var poses = rstItem.PosId.Split("-");
                    if (poses.Count() == 3)
                    {
                        int x = int.Parse(poses[0]);
                        int y = int.Parse(poses[1]);
                        int id = int.Parse(poses[2]);
                        AddId(new Point(x, y), id, 200);
                    }
                }
            }
            try
            {
                _results.Sort((x, y) => File.GetCreationTime(x.FullPath) > File.GetCreationTime(y.FullPath) ? 1 : -1);
                //_results.OrderBy(r=>File.GetCreationTime(r.FullPath));
                List<ResultInfo> orderResult = new();
                orderResult.AddRange(_results.Where((d) => d.Id > 0).OrderBy(d => d.Id));
                orderResult.AddRange(_results.Where(d => d.SId.StartsWith("边缘")).OrderBy(d => int.Parse(d.SId.Substring(2))));
                orderResult.AddRange(_results.Where(d => d.SId.Contains("正面")));
                orderResult.AddRange(_results.Where(d => d.SId.Contains("背面")));
                LbResults.ItemsSource = orderResult;
                LbResults.SelectedIndex = 0;
                LbResults.ScrollIntoView(LbResults.SelectedItem);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return;
            }


        }
    }

    public void DispId()
    {
        List<PointParam> pointParams = new()
        {
            new PointParam { Radius = 0, Num = 1, StartAngle = 0, EndAngle = 360 },
            new PointParam { Radius = 37.5, Num = 4, StartAngle = -90, EndAngle = -450 },
            new PointParam { Radius = 75, Num = 12, StartAngle = -90, EndAngle = -450 },
            new PointParam { Radius = 112.5, Num = 12, StartAngle = -90, EndAngle = -450 }
        };
        int temp = 0;
        foreach (var pointParam in pointParams)
        {
            var centerx = _imageWidth / 2d;
            var centery = _imageHeight / 2d;
            for (int i = 0; i < pointParam.Num; i++)
            {
                double angle = pointParam.StartAngle + (pointParam.EndAngle - pointParam.StartAngle) * i / (pointParam.Num);
                double x = pointParam.Radius * 10 * Math.Cos(angle * Math.PI / 180d) + centerx;
                double y = pointParam.Radius * 10 * Math.Sin(angle * Math.PI / 180d) + centery;
                if (temp == 0)
                {
                    AddId(new Point { X = x, Y = y }, 1, 200);
                }
                else if (temp == 1)
                {
                    AddId(new Point { X = x, Y = y }, 2 + i, 200);
                }
                else if (temp == 2)
                {
                    AddId(new Point { X = x, Y = y }, 6 + i, 200);
                }
                else
                {
                    AddId(new Point { X = x, Y = y }, 18 + i, 200);
                }
            }

            temp++;
        }
    }

    public int CalId(string posId)
    {
        List<PointId> points = new List<PointId>();
        List<PointParam> pointParams = new List<PointParam>();
        pointParams.Add(new PointParam { Radius = 0, Num = 1, StartAngle = 0, EndAngle = 360 });
        pointParams.Add(new PointParam { Radius = 37.5, Num = 4, StartAngle = -90, EndAngle = -450 });
        pointParams.Add(new PointParam { Radius = 75, Num = 12, StartAngle = -90, EndAngle = -450 });
        pointParams.Add(new PointParam { Radius = 112.5, Num = 12, StartAngle = -90, EndAngle = -450 });

        int temp = 0;
        foreach (var pointParam in pointParams)
        {
            var centerx = _imageWidth / 2d;
            var centery = _imageHeight / 2d;
            for (int i = 0; i < pointParam.Num; i++)
            {
                double angle = pointParam.StartAngle + (pointParam.EndAngle - pointParam.StartAngle) * i / (pointParam.Num);
                double x = pointParam.Radius * 10 * Math.Cos(angle * Math.PI / 180d);
                double y = pointParam.Radius * 10 * Math.Sin(angle * Math.PI / 180d);
                if (temp == 0)
                {
                    points.Add(new PointId { X = x + centerx, Y = y + centery, Id = 1 });
                }
                else if (temp == 1)
                {
                    points.Add(new PointId { X = x + centerx, Y = y + centery, Id = 2 + i });
                }
                else if (temp == 2)
                {
                    points.Add(new PointId { X = x + centerx, Y = y + centery, Id = 6 + i });
                }
                else
                {
                    points.Add(new PointId { X = x + centerx, Y = y + centery, Id = 18 + i });
                }
            }

            temp++;
        }
        if (posId.Contains("-"))
        {
            var pos = posId.Split("-");
            int x = int.Parse(pos[0]);
            int y = int.Parse(pos[1]);
            var p1 = points.Where(p => Math.Abs(p.X - x) < 20 && Math.Abs(p.Y - y) < 20);
            if (p1.Any())
            {
                return p1.First().Id;
            }
        }
        return 0;
    }

    public int GetId(string posId)
    {
        if (posId.Contains("-"))
        {
            var temps = posId.Split("-");
            if (temps.Length == 3)
            {
                if (int.TryParse(temps[2], out int id)) return id;
            }
        }
        return 0;
    }

    public int GetSortId(string posId)
    {
        if (posId.Contains("-"))
        {
            var temps = posId.Split("-");
            if (temps.Length == 3)
            {
                if (int.TryParse(temps[2], out int id)) return 500 + id;
            }
        }
        else if (posId.Contains("正面中心"))
        {
            if (posId.Count() == 6 && int.TryParse(posId.Substring(4, 2), out int id))
            {
                return id + 100;
            }
        }
        else if (posId.Contains("正面边缘"))
        {
            if (posId.Count() == 6 && int.TryParse(posId.Substring(4, 2), out int id))
            {
                return id + 200;
            }
        }
        else if (posId.Contains("背面中心"))
        {
            if (posId.Count() == 6 && int.TryParse(posId.Substring(4, 2), out int id))
            {
                return id + 300;
            }
            else { return 300; }
        }
        else if (posId.Contains("背面边缘"))
        {
            if (posId.Length == 6 && int.TryParse(posId.AsSpan(4, 2), out int id))
            {
                return id + 400;
            }
            else return 400;
        }
        return 0;
    }

    private void BtShort_Click(object sender, RoutedEventArgs e)
    {
        DefectView defectView = new DefectView();
        defectView.Owner = this;
        defectView.ShowInTaskbar = false;
        defectView.Show();
    }

    private void LbResults_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
    {
        if (_defectClsList is null) return;
        if (_defectClsList.Any(d => d.ShortKey == e.Key.ToString()) && LbResults.SelectedItem is ResultInfo rst)
        {
            var decto = _defectClsList.First(d => d.ShortKey == e.Key.ToString());

            if (rst.Defects.Any(d1 => d1.DefectName == decto.DefectName))
            {
                var defc = rst.Defects.First(d1 => d1.DefectName == decto.DefectName);
                rst.Defects.Remove(defc);
            }
            else
            {
                if (!rst.Defects.Any(d1 => d1.BinCode == 0))
                {
                    if (rst.Defects.Count > 0 && decto.BinCode == 0)
                    {
                        //var ls = rst.Defects.ToList();
                        //var sss = ls.FindAll(m => m.BinCode != 0);
                        //sss.ForEach(m => ls.Remove(m));
                        //ls.ForEach(m => rst.Defects.Add(m));
                    }
                    else
                    {
                        rst.Defects.Add(new DefectCls { BinCode = decto.BinCode, DefectName = decto.DefectName, ShortKey = decto.ShortKey });
                    }
                }
            }
            using var db = new ResultDb();
            if (rst != null)
            {
                if (rst.Defects.Any(r1 => r1.BinCode > 0))
                {
                    rst.IsOK = false;
                }
                else if (rst.Defects.Any(r1 => r1.BinCode == 0))
                {
                    rst.IsOK = true;
                }
                else { rst.IsOK = null; }
                if (db.Results.Any(r => r.FullPath == rst.FullPath))
                {
                    var upd = db.Results.Include(r => r.Defects).First(r => r.FullPath == rst.FullPath);
                    upd.IsOK = rst.IsOK;
                    upd.Defects.Clear();
                    foreach (var item in rst.Defects)
                    {
                        upd.Defects.Add(new DefectCls { BinCode = item.BinCode, DefectName = item.DefectName, ShortKey = item.ShortKey });
                    }
                }
                else
                    db.Add<ResultInfo>(rst);
                db.SaveChanges();
            }
            //if (LbResults.SelectedIndex < LbResults.Items.Count - 2)
            // LbResults.SelectedIndex += 1;
        }
    }

    private void BtLog_Click(object sender, RoutedEventArgs e)
    {
        SystemSetView systemSetView = new SystemSetView();

        systemSetView.ShowDialog();
    }

    private void CbBoxID_DropDownOpened(object sender, EventArgs e)
    {
        var dires = Directory.EnumerateDirectories(_imagePath).OrderByDescending(m => new DirectoryInfo(m).CreationTime).Select(dire => new DirectoryInfo(dire).Name);
        var ldir = dires.ToList();
        ldir.Add(string.Empty);
        CbBoxID.ItemsSource = ldir;
        CbBoxID.SelectedIndex = 0;
    }


    private HDrawingObject? _drawingObj;

    /// <summary>
    /// 创建部分图像
    /// </summary>
    private void GenPartImage(string filePath)
    {
        string? dir = Path.GetDirectoryName(filePath);
        string fileName = Path.GetFileNameWithoutExtension(filePath);
        if ((fileName == "反面中心" || fileName == "正面中心") && dir != null)
        {
            HImage image = new HImage(filePath);
            image.GetImageSize(out int width, out int height);
            int num = 4, radius1 = 1200;
            int centerx = width / 2 + 50, centery = height / 2;
            for (int i = 0; i < num; i++)
            {
                HRegion hRegion1 = new HRegion();

                hRegion1.GenCircleSector(centery, centerx, radius1, i * 2 * Math.PI / num, (i + 1) * 2 * Math.PI / num);
                HImage hImage1 = image.ReduceDomain(hRegion1);
                HImage hImage2 = hImage1.CropDomain();
                hImage2.WriteImage("bmp", 0, Path.Combine(dir, $"{fileName}{i + 1:d2}"));
            }
            File.Delete(filePath);
        }
        //if ((fileName == "反面边缘" || fileName == "正面边缘") && dir != null)
        //{
        //    HImage image = new HImage(filePath);
        //    image.GetImageSize(out int width, out int height);
        //    int num = 12, radius1 = 1350, radius2 = 1000;
        //    int centerx = width / 2 + 50, centery = height / 2;
        //    for (int i = 0; i < num; i++)
        //    {
        //        HRegion hRegion1 = new HRegion();
        //        HRegion hRegion2 = new HRegion();
        //        HRegion hRegion3;
        //        hRegion1.GenCircleSector(centery, centerx, radius1, i * 2 * Math.PI / num, (i + 1) * 2 * Math.PI / num);
        //        hRegion2.GenCircleSector(centery, centerx, radius2, i * 2 * Math.PI / num, (i + 1) * 2 * Math.PI / num);
        //        hRegion3 = hRegion1.Difference(hRegion2);
        //        HImage hImage1 = image.ReduceDomain(hRegion3);
        //        HImage hImage2 = hImage1.CropDomain();
        //        hImage2.WriteImage("bmp", 0, Path.Combine(dir, $"{fileName}{i + 1:d2}"));
        //    }
        //    File.Delete(filePath);
        //}
    }

    private void BtHorizontal1_Click(object sender, RoutedEventArgs e)
    {
        mDisp.CanDraw = true;
        mDisp.MeasureResults = _measureRsults;
        var g = Guid.NewGuid().ToString();
        mDisp.RegisterDraw((m, s) =>
        {
            if (m.Count != 2) return;
            m[0].GetRegion().AreaCenter(out double r1, out double c1);
            m[1].GetRegion().AreaCenter(out double r2, out double c2);

            HOperatorSet.DistancePp(r1, c1, r2, c2, out HTuple distance);
            if (_measureRsults.Count == 0)
            {
                _measureRsults = new List<MeasureResult>();
                var sss = _dicAllMeasures[_curPath];
                sss?.ForEach(m => _measureRsults.Add(m));
            }

            var rst = _measureRsults.Find(m => m.MeasureID == s);
            if (rst.ResultLine == null)
            {
                System.Windows.Shapes.Line rstLine = new()
                {
                    X1 = c1,
                    Y1 = r1,
                    X2 = c2,
                    Y2 = r2,
                    Stroke = Brushes.Red,
                    StrokeThickness = 6,
                    StrokeDashArray = new DoubleCollection() { 2, 2 }
                };
                this.mDisp.CvDisplay2.Children.Add(rstLine);
                rst.ResultLine = rstLine;
            }
            rst.Distance = distance.D * GlobalData.Instance.RatioParam.X50Ratio;
            rst.ResultLine.X1 = c1;
            rst.ResultLine.Y1 = r1;
            rst.ResultLine.X2 = c2;
            rst.ResultLine.Y2 = r2;
            rst.TextPoint = new Point(rst.ResultLine.X1 + 10, (rst.ResultLine.Y2 - rst.ResultLine.Y1) / 2 + rst.ResultLine.Y1 - 40);
            rst.AllLines = new();
            rst.AllLines.Add(rst.ResultLine);
            rst.AllLines.Add(m[0].GetLine());
            rst.AllLines.Add(m[1].GetLine());
            mDisp.ClearVisual();
            foreach (var item in _measureRsults)
            {
                mDisp.DisplayText($"{item.Distance:f2}um", Colors.Red, 60, item.TextPoint);
            }

        }, 10, g);
    }



    private void BtVertical1_Click(object sender, RoutedEventArgs e)
    {
        mDisp.CanDraw = true;
        mDisp.MeasureResults = _measureRsults;
        var g = Guid.NewGuid().ToString();
        mDisp.RegisterDraw((m, s) =>
        {
            if (m.Count != 2) return;
            m[0].GetRegion().AreaCenter(out double r1, out double c1);
            m[1].GetRegion().AreaCenter(out double r2, out double c2);

            HOperatorSet.DistancePp(r1, c1, r2, c2, out HTuple distance);


            if (_measureRsults.Count == 0)
            {
                _measureRsults = new List<MeasureResult>();
                var sss = _dicAllMeasures[_curPath];
                sss?.ForEach(m => _measureRsults.Add(m));
            }


            var rst = _measureRsults.Find(m => m.MeasureID == s);
            if (rst.ResultLine == null)
            {
                System.Windows.Shapes.Line rstLine = new()
                {
                    X1 = c1,
                    Y1 = r1,
                    X2 = c2,
                    Y2 = r2,
                    Stroke = Brushes.Red,
                    StrokeThickness = 6,
                    StrokeDashArray = new DoubleCollection() { 2, 2 }
                };
                this.mDisp.CvDisplay2.Children.Add(rstLine);
                rst.ResultLine = rstLine;
            }
            rst.Distance = distance.D * GlobalData.Instance.RatioParam.X50Ratio;
            rst.ResultLine.X1 = c1;
            rst.ResultLine.Y1 = r1;
            rst.ResultLine.X2 = c2;
            rst.ResultLine.Y2 = r2;
            rst.TextPoint = new Point(rst.ResultLine.X1 + 50, (rst.ResultLine.Y2 - rst.ResultLine.Y1) / 2 + rst.ResultLine.Y1 - 100);

            rst.AllLines = new();
            rst.AllLines.Add(rst.ResultLine);
            rst.AllLines.Add(m[0].GetLine());
            rst.AllLines.Add(m[1].GetLine());

            mDisp.ClearVisual();
            foreach (var item in _measureRsults)
            {
                mDisp.DisplayText($"{item.Distance:f2}um", Colors.Red, 60, item.TextPoint);
            }

        }, 20, g);
    }

    private void BtVertical2_Click(object sender, RoutedEventArgs e)
    {
        mDisp.CanDraw = true;

        var g = Guid.NewGuid().ToString();

        mDisp.RegisterDraw((s) =>
        {
            mDisp.ClearVisual();
            foreach (var item in _measureRsults)
            {
                mDisp.DisplayText($"{item.Distance:f2}um", Colors.Red, 60, item.TextPoint);
            }

        }, 30, g);
    }

    private HImage ProcessImage(HImage image)
    {
        HImage tmp;
        tmp = image.ScaleImage(1.5, 0);
        tmp = tmp.MultImage(tmp, 0.005, 0);
        tmp = tmp.ScaleImage(1.5, 0);
        tmp = tmp.MultImage(tmp, 0.005, 0);
        tmp = tmp.MeanImage(6, 6);
        return tmp;
    }

    private void BtDelRoi_Click(object sender, RoutedEventArgs e)
    {
        mDisp.CanDraw = false;
        mDisp.Opacity = 1;
        mDisp.ClearAllROI();
        mDisp.ClearVisual();
        _measureRsults.Clear();
        if(_dicAllMeasures.ContainsKey(_curPath))
            _dicAllMeasures[_curPath].Clear();
    }

    private void BtCalib_Click(object sender, RoutedEventArgs e)
    {
        CalibView calibView = new CalibView();

        calibView.ShowDialog();



    }

    private void BtMeasureData_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            List<MeasureExcel> measureDatas;

            var dicdata=new Dictionary<string, List<MeasureExcel>>();
            if (CbBoxID.SelectedItem is string boxpath)
            {
                var picPath = Path.Combine(_imagePath, boxpath);

                var files = Directory.EnumerateDirectories(picPath).ToList();

                for (int i = 0; i < files.Count; i++)
                {
                    var picFiles = Directory.GetFiles(files[i]).ToList().Where(m =>
                    {

                        var s = Path.GetFileName(m);

                        if (s.Split('-').Count() == 3 && (m.EndsWith("bmp")|| m.EndsWith("png")|| m.EndsWith("jpg")|| m.EndsWith("jpeg")))
                            return true;
                        else
                            return false;
                    }).ToList();


                    if (!_dicAllMeasures.ContainsKey(_curPath) && _measureRsults.Count != 0)
                    {
                        List<MeasureResult> mrs = new List<MeasureResult>();
                        _measureRsults.ForEach(m => mrs.Add(m));
                        _dicAllMeasures.Add(_curPath, mrs);
                        _measureRsults.Clear();
                        _dicAllRecordImage.Add(_curPath, mDisp.GetWindowContent());
                    }

                    foreach (var item in picFiles)
                    {
                        if (!_dicAllMeasures.ContainsKey(item))
                            continue;
                        foreach (var data in _dicAllMeasures[item])
                        {
                            if (dicdata.ContainsKey(data.WaferName))
                                dicdata[data.WaferName].Add(new MeasureExcel() { Distance = data.Distance.ToString("f3"), MeasureType = data.ResultType });
                           else
                            {
                                measureDatas = new();
                                measureDatas.Clear();
                                measureDatas.Add(new MeasureExcel() { Distance = data.Distance.ToString("f3"), MeasureType = data.ResultType });
                                dicdata.Add(data.WaferName, measureDatas);
                            }
                        }
                    }
                }

                var datafile = Path.Combine(_measurePath, "datas");
                var picfile = Path.Combine(_measurePath, "images", $"{boxpath}");

                if (!File.Exists(datafile))
                {
                    Directory.CreateDirectory(datafile);
                }
              
                if (!File.Exists(picfile))
                {
                    Directory.CreateDirectory(picfile);
                }
                SaveMeasureData(dicdata, datafile);
                SaveRecord(_dicAllRecordImage, picfile);
                MessageBox.Show("量测数据导出完成！");
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("量测数据导出失败！");
        }
    }


    private bool SaveMeasureData(Dictionary<string, List<MeasureExcel>> datas, string filename)
    {
        if (datas.Count == 0) return false;
        try
        {
            IWorkbook worker = new XSSFWorkbook();
            ISheet sheet = worker.CreateSheet("sheet1");
            IRow row1 = sheet.CreateRow(0);
            sheet.DefaultColumnWidth = 100 * 256;
            sheet.DefaultRowHeight = 20 * 20;
            row1.CreateCell(0).SetCellValue("类型");
            row1.CreateCell(1).SetCellValue("名称");
            row1.CreateCell(2).SetCellValue("X坐标");
            row1.CreateCell(3).SetCellValue("Y坐标");
            row1.CreateCell(4).SetCellValue("面积");
            row1.CreateCell(5).SetCellValue("长度（um）");
            row1.CreateCell(6).SetCellValue("夹角");
            row1.CreateCell(7).SetCellValue("周长");
            foreach (var item in datas)
            {
                for (int i = 0; i < item.Value.Count; i++)
                {
                    IRow row = sheet.CreateRow(i + 1);

                    row.CreateCell(0).SetCellValue(item.Value[i].MeasureType);
                    row.CreateCell(5).SetCellValue(item.Value[i].Distance);
                }
                if (File.Exists(Path.Combine(filename,item.Key) + ".xlsx"))
                    File.Delete(Path.Combine(filename, item.Key) + ".xlsx");

                FileStream files = new FileStream(Path.Combine(filename, item.Key) + ".xlsx", FileMode.Create);
                worker.Write(files);
                files.Close();
            }
            return true;
        }
        catch (Exception ex)
        {

            return false;
        }

    }


    private void SaveRecord(Dictionary<string, RenderTargetBitmap> records, string path)
    {
        try
        {
            foreach (var item in records)
            {
                var s = Path.GetFileNameWithoutExtension(item.Key).Split('-')[2];
                var wafername = Directory.GetParent(item.Key).Name;
                JpegBitmapEncoder encoder = new();
                encoder.Frames.Add(BitmapFrame.Create(item.Value));
                if (!File.Exists(Path.Combine(path, wafername)))
                    Directory.CreateDirectory(Path.Combine(path, wafername));
                // save file to disk
                using (FileStream fs = File.Open(Path.Combine(path,wafername, s) + $".jpg", FileMode.OpenOrCreate))
                {
                    encoder.Save(fs);
                }
            }
        }
        catch (Exception ex)
        {

            Debug.WriteLine(ex.Message);
        }
    }

    private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        _machineData.ID = CbMaineID.SelectedIndex+1;
        Load_ID();
    }
}



public class ExcelInfo
{
    public string Name { get; set; }
    public string Description { get; set; }
}

public class WaferInfo
{
    public string Id { get; set; } = string.Empty;
    public bool IsShow { get; set; }
    public bool? IsOk { get; set; }
    public string FilePath { get; set; } = string.Empty;
}
public class MeasureExcel
{
    public string MeasureType { get; set; }

    public string Distance { get; set; }
}
public class PointParam
{
    /// <summary>
    /// 半径
    /// </summary>
    public double Radius { get; set; }

    /// <summary>
    /// 个数
    /// </summary>
    public double Num { get; set; }

    /// <summary>
    /// 起始角度
    /// </summary>
    public double StartAngle { get; set; }

    /// <summary>
    /// 结束角度
    /// </summary>
    public double EndAngle { get; set; }
}

public class PointId
{
    public int Id { get; set; }
    public double X { get; set; }
    public double Y { get; set; }
}